package cn.edu.cuit.elena.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

public class FileGenerator
{
    public static void generatePropertyFile( Configurable configurable, String filePath )
    {
        Map<String, String> properties = configurable.getProperties();
        Writer writer = openWriter( filePath );
        try
        {
            for( String key : properties.keySet() )
            {
                writer.write( key + SackConstants.EQUAL_SIGN + properties.get( key ) + "\n" );
            }

            closeWriter( writer );
        }
        catch( IOException e )
        {
            throw new FileHandlingException( e.getMessage() );
        }
    }

    private static void closeWriter( Writer writer )
    {
        try
        {
            writer.close();
        }
        catch( Exception e )
        {
            throw new FileHandlingException( e.getMessage() );
        }
    }

    private static Writer openWriter( String filePath )
    {
        File file = new File( filePath );
        try
        {
            Writer out = new FileWriter( file );
            BufferedWriter bufferedWriter = new BufferedWriter( out );
            return bufferedWriter;
        }
        catch( IOException e )
        {
            throw new FileHandlingException( e.getMessage() );
        }
    }
}
